package com.railway.switchs.service.impl.message;

import com.railway.switchs.base.BaseResponse;
import com.railway.switchs.domain.request.SendEmailRequest;
import com.railway.switchs.domain.response.SendEmailResponse;
import com.railway.switchs.enums.EnumReturnResult;
import com.railway.switchs.service.message.ISendEmailService;
import com.railway.switchs.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import java.io.File;
import java.util.Date;

/**
 * @ClassName SendEmailServiceImpl
 * @Author Lonely_man
 * @Date 2020/4/12 14:51
 * @Version 1.0
 **/
@Slf4j
@Service("sendEmailService")
public class SendEmailServiceImpl  implements ISendEmailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String fromAccount;

    @Override
    public SendEmailResponse sendEmail(SendEmailRequest request) {
        SendEmailResponse response = new SendEmailResponse();
        try{
            if(EnumReturnResult.RETURN_404.getCode().equals(checkParams(request).getCode())){
                log.error(checkParams(request).getMsg());
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg(checkParams(request).getMsg());
                return response;
            }
            MimeMessageHelper mimeMessageHelper = buildMail(request);
            //正式发送邮件
            mailSender.send(mimeMessageHelper.getMimeMessage());
            //记录邮件发送日志
            response.setCode(EnumReturnResult.RETURN_200.getCode());
        }catch (Exception e){
            log.error("发送邮件失败",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("发送邮件失败");
        }
        return response;
    }
    /**
     * 构建复杂邮件
     * @param request
     */
    private MimeMessageHelper buildMail(SendEmailRequest request) throws Exception{
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
        request.setFrom(fromAccount);
        mimeMessageHelper.setFrom(new InternetAddress((StringUtil.isBlank(request.getNickName()) ? request.getFrom() : request.getNickName()) + " <" + request.getFrom() + ">"));
        mimeMessageHelper.setTo(request.getTo().split(","));
        mimeMessageHelper.setSubject(request.getSubject());
        mimeMessageHelper.setText(request.getText(),request.isHtmlText());
        mimeMessageHelper.setSentDate(new Date());
        if(StringUtil.isNotBlank(request.getCc())){
            mimeMessageHelper.setCc(request.getCc().split(","));
        }
        if(StringUtil.isNotBlank(request.getBcc())){
            mimeMessageHelper.setBcc(request.getBcc().split(","));
        }
        if(StringUtil.isNotNull(request.getSendDate())){
            mimeMessageHelper.setSentDate(request.getSendDate());
        }
        if(null != request.getAppendixs() && 0 != request.getAppendixs().size()){
            for(String fileName : request.getAppendixs().keySet()){
                File file = new File(request.getAppendixs().get(fileName));
                mimeMessageHelper.addAttachment(fileName,file);
            }
        }
        return mimeMessageHelper;
    }

    /**
     * 校验参数
     * @param request
     * @return
     */
    public BaseResponse checkParams(SendEmailRequest request){
        BaseResponse response = new BaseResponse();
        response.setCode(EnumReturnResult.RETURN_404.getCode());
        if(StringUtil.isBlank(request.getNickName())){
            response.setMsg("邮件发送人不能为空");
            return response;
        }
        if(StringUtil.isBlank(request.getTo())){
            response.setMsg("邮件接收人不能为空");
            return response;
        }
        if(StringUtil.isBlank(request.getSubject())){
            response.setMsg("邮件主题不能为空");
            return response;
        }
        if(StringUtil.isBlank(request.getText())){
            response.setMsg("邮件内容不能为空");
            return response;
        }
        response.setCode(EnumReturnResult.RETURN_200.getCode());
        return response;
    }
}
